package cn.edu.cdu.argorithm.impl;

import cn.edu.cdu.argorithm.IValidPalindrome;

public class ValidPalindromeSolutions {
    public static class Solution1 implements IValidPalindrome {
        @Override
        public boolean isPalindrome(String s) {
            StringBuffer sgoods = new StringBuffer();
            int n = s.length();
            for(int i = 0; i < n; i++) {
                char ch = s.charAt(i);
                if(Character.isLetterOrDigit(ch)) {
                    sgoods.append(Character.toLowerCase(ch));
                }
            }
            StringBuffer reverse = new StringBuffer(sgoods);
            return sgoods.compareTo(reverse.reverse()) == 0;
        }
    }

    public static class Solution2 implements IValidPalindrome {

        @Override
        public boolean isPalindrome(String s) {
            StringBuffer sgoods = new StringBuffer();
            int n = s.length();
            for (int i = 0; i < n; i++) {
                char ch = s.charAt(i);
                if(Character.isLetterOrDigit(ch)){
                    sgoods.append(Character.toLowerCase(ch));
                }
            }
            n = sgoods.length();
            int left = 0, right = n - 1;
            while(left < right) {
                if (sgoods.charAt(left) != sgoods.charAt(right)) {
                    return false;
                }
                ++left;
                --right;
            }
            return true;
        }
    }

    public static class Solution3 implements IValidPalindrome {
        @Override
        public boolean isPalindrome(String s) {
            int n = s.length(), left = 0, right = n - 1;
            while(left < right) {
                 while(left < right && !Character.isLetterOrDigit(s.charAt(left))) {
                     ++left;
                 }
                 while(left < right && !Character.isLetterOrDigit(s.charAt(right))){
                     --right;
                 }
                 if(left < right && Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
                     return false;
                 }
                 ++left;
                 --right;
            }
            return true;
        }
    }
}
